package com.example.examapp.service.impl;

import com.example.examapp.enums.QuestionType;
import com.example.examapp.model.Answer;
import com.example.examapp.model.Question;
import com.example.examapp.model.QuestionResult;
import com.example.examapp.service.AnswerService;
import org.lzx.base.common.Result;
import org.lzx.base.service.impl.BaseServiceImpl;
import org.lzx.base.utils.ResultUtil;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @package com.example.examapp.service.impl
 * @data 2022/12/4 13:21
 */
@Service
public class AnswerServiceIpml extends BaseServiceImpl<Answer> implements AnswerService {

    @Override
    public Result result() {
        List<Answer> answers = super.mongoTemplate.findAll(Answer.class);
        List<String> questionIds = answers.stream().map(answer -> answer.getQuestionId()).distinct().collect(Collectors.toList());
        List<Question> questions = super.mongoTemplate.find(new Query(Criteria.where("id").in(questionIds.toArray())), Question.class);
        Map<String, Question> stringQuestionMap = questions.stream().collect(Collectors.toMap(question -> question.getId(), question -> question));
        Map<String, List<Answer>> listMap = answers.stream().collect(Collectors.groupingBy(answer -> answer.getQuestionId()));
        List<QuestionResult> questionResults = listMap.keySet().stream().map(key -> {
            QuestionResult questionResult = new QuestionResult();
            questionResult.setQuestion(stringQuestionMap.get(key));
            questionResult.setAnswers(listMap.get(key));
            Map<String, List<Answer>> results = listMap.get(key).stream().collect(Collectors.groupingBy(answer -> answer.getAnswer()));
            questionResult.setResults(results);
            return questionResult;

        }).collect(Collectors.toList());
        return ResultUtil.success(questionResults);
    }
}
